/*---------------------------------------------------------------------
 * File name: ulink.h
 *
 * Copyright (c) <2020-2022>, <ChenLong>
 *
 * All rights reserved.
 *
 * Author: ChenLong
 * Email: worldlong@foxmail.com
 *--------------------------------------------------------------------*/
#pragma once
/*
 */
#include <stdint.h>
/*
*/
#define ULINK_MSG_HEAD      0xfa
#define ULINK_MSG_SIZE_MIN  5
    
typedef enum 
{
  STATE_HEAD,
  STATE_LEN,
  STATE_ID_LSB,
  STATE_ID_MSB,
  STATE_DATA,
  STATE_CHECK
}state_t;
/*
*/
class ULink
{
public:
  ULink() : 
    _head(ULINK_MSG_HEAD),
    _state(STATE_HEAD)
  {
    msg.head = _head;
  }
  
  ULink(uint8_t head) : 
    _head(head),
    _state(STATE_HEAD)
  {
    msg.head = _head;
  }

  //Message frame definition
  struct
  {
    uint8_t head;
    uint8_t len;
    uint16_t id;
    uint8_t data[256];
    uint8_t check;
  }msg;
  
  bool parse(uint8_t data);
  int packet(uint8_t* buff);
  void build_start(uint16_t id);
  void build_end();
  uint8_t check_calculate();
  void data_copy(uint8_t *buff, int offset, int num);
  void insert_u8(uint8_t data);
  void insert_u16(uint16_t data);
  void insert_u24(uint32_t data);
  void insert_u32(uint32_t data);
  void insert_f32(float data);
  void insert_bytes(uint8_t *buffer, int number);
  void insert_string(char *str);
  
  uint8_t  extract_u8(int index);
  uint16_t extract_u16(int index);
  uint32_t extract_u24(int index);
  uint32_t extract_u32(int index);
  float extract_f32(int index);
  uint32_t extract_bytes(uint8_t *buffer, int number, int index);
  uint32_t extract_string(char *str, int index);
  
private:
  uint8_t   _head;
  state_t   _state;
  int       _count;
  bool      check();
};


